package com.offcn.seckill.timer;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.offcn.seckill.dao.SeckillGoodsMapper;
import com.offcn.seckill.pojo.SeckillGoods;
import com.offcn.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Component
public class SeckillGoodsPushToRedis {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired(required = false)
    private SeckillGoodsMapper goodsMapper;

    @Scheduled(cron = "0/20 * * * * ?")
    public void addGoodsToRedis(){
//        System.out.println("add function running" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        // 获取时间段的集合
        List<Date> dateMenus = DateUtil.getDateMenus();
        for (Date startTime : dateMenus) {
            // 开始时间段
            String timer = DateUtil.date2Str(startTime);
            // select * from tb_seckill_goods
            //where start_time >= '2021-09-24 10:00:00' && end_time < '2021-09-24 12:00:00'
            // and status = '1'
            // and id not in (1,2,3)  # 1，2，3 已经在缓存中
            // 获取开始时间，转为 年月日的格式的字符串
            String seckillStartTime = DateUtil.date2StrFull(startTime);// 时间段的开始时间
            Date endTime = DateUtil.addDateHour(startTime, 2);
            String seckillEndTime = DateUtil.date2StrFull(endTime); // 活动结束的时间

            QueryWrapper<SeckillGoods> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status","1");
            queryWrapper.ge("start_time",seckillStartTime);
            queryWrapper.lt("end_time",seckillEndTime);
            queryWrapper.gt("stock_count",0); // 有库存

            Set keys = redisTemplate.boundHashOps("seckillGoods_" + timer).keys();
            if (keys != null && keys.size() > 0){
                // and id not in (1,2,3)  # 1，2，3 已经在缓存中
                queryWrapper.notIn("id",keys);
            }

            List<SeckillGoods> seckillGoods = goodsMapper.selectList(queryWrapper);

            if (seckillGoods != null) {
                for (SeckillGoods seckillGood : seckillGoods) {
                    redisTemplate.boundHashOps("seckillGoods_" + timer).put(seckillGood.getId(),seckillGood);
                    redisTemplate.expireAt("seckillGoods_" + timer,endTime); // 失效时间是活动的结束时间

                    // 每次被抢购的数据 从 该列表中体现
                    Long[] ids = pushIds(seckillGood.getStockCount(), seckillGood.getId());
                    redisTemplate.boundListOps("seckillGoodsCountList_" + seckillGood.getId()).leftPush(ids);
                }
            }
        }
    }

    private Long[] pushIds(int length,Long id){
        Long[] ids = new Long[length];
        for (int i = 0; i < length; i++) {
            ids[i] = id;
        }
        return ids;  // ==>  5个id是10的商品 => [10,10,10,10,10]
    }
}
